package com.myl.web.controller.store;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.util.List;

import javax.servlet.Servlet;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.lang3.StringUtils;

import com.github.pagehelper.PageInfo;
import com.myl.domain.store.Question;
import com.myl.domain.store.Catalog;
import com.myl.domain.store.Company;
import com.myl.domain.store.Course;
import com.myl.service.store.QuestionService;
import com.myl.service.store.impl.QuestionServiceImp;
import com.myl.utils.BeanUtil;
import com.myl.web.controller.BaseServlet;

/**
 * Servlet implementation class QuestionServlet
 */
@WebServlet("/store/question")
public class QuestionServlet extends BaseServlet{
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public QuestionServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String operation = request.getParameter("operation");
		if("list".equals(operation)){
			
			this.list(request,response);
			
		}else if ("toAdd".equals(operation)) {
			this.toAdd(request, response);
		}else if ("save".equals(operation)) {
				try {
					this.save(request, response);
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}	
		}else if ("toEdit".equals(operation)) {
	         this.toEdit(request,response);
        }else if ("edit".equals(operation)) {
        	try {
				this.edit(request,response);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}else if ("delete".equals(operation)) {
        	this.delete(request,response);
		}else if ("TotestFileUpload".equals(operation)) {
        	this.TotestFileUpload(request,response);
		}else if ("testUpload".equals(operation)) {
        	try {
        		this.testUpload(request, response);
			} catch (FileUploadException e) {
				e.printStackTrace();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}else if ("downloadReport".equals(operation)) {
        	this.downloadReport(request,response);
		}
	
	}

	private void downloadReport(HttpServletRequest request, HttpServletResponse response) throws IOException {
		response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
		response.addHeader("Content-Disposition", "attachment;fileName=dowload.xlsx");

		/*String fileName = new String("测试文件名.xlsx".getBytes(),"iso8859-1");
		response.addHeader("Content-Disposition", "attachment;fileName="+fileName);*/
		ByteArrayOutputStream   os = questionService.getReport();
		ServletOutputStream sos  =response.getOutputStream();
		os.writeTo(sos);
		sos.flush();
		
	}

	private void testUpload(HttpServletRequest request, HttpServletResponse response) throws Exception {
		

	   	 if(ServletFileUpload.isMultipartContent(request)){
				//创建磁盘工厂
				DiskFileItemFactory factory = new DiskFileItemFactory();
				//通过servlet对象上传核心对象
				ServletFileUpload fileUpload = new ServletFileUpload(factory);
				//从reque 中获取对象
				List<FileItem> fileItems = fileUpload.parseRequest(request);		
				for(FileItem item: fileItems){
					System.out.println(item);
					if(!item.isFormField()){
						item.write(new File(this.getServletContext().getRealPath("upload"),item.getName()));
					}
				}
			}
	   	 	
			list(request, response);	
		
	}

	private void TotestFileUpload(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.getRequestDispatcher("/WEB-INF/pages/store/question/testFileUpload.jsp").forward(request, response);
		
	}

	private void delete(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
		Question question = BeanUtil.fillBean(request, Question.class,"yyyy-MM-dd");
		QuestionService questionService = new QuestionServiceImp();
		questionService.delete(question);
		list(request, response);
		
	}

	private void edit(HttpServletRequest request, HttpServletResponse response) throws Exception {
   	 if(ServletFileUpload.isMultipartContent(request)){
			//创建磁盘工厂
			DiskFileItemFactory factory = new DiskFileItemFactory();
			//通过servlet对象上传核心对象
			ServletFileUpload fileUpload = new ServletFileUpload(factory);
			//从reque 中获取对象
			List<FileItem> fileItems = fileUpload.parseRequest(request);
			
			boolean flag = false;
			for(FileItem item: fileItems){
				if(StringUtils.isNotBlank(item.getName())){
					flag = true;
					break;
				}
			}
			
			Question question = BeanUtil.fillBean(fileItems, Question.class);
			questionService.update(question,flag);
			
			for(FileItem item: fileItems){
				if(!item.isFormField()){
					item.write(new File(this.getServletContext().getRealPath("upload"),question.getId()));
				}
			}
			
		}
				
		list(request, response);
	}

	private void toEdit(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {

		String id = request.getParameter("id");
		QuestionService questionService = new QuestionServiceImp();
		Question question = questionService.findById(id);
		request.setAttribute("question", question);
		
		List<Company> companyList = companyService.findAll();
		List<Catalog> catalogList = catalogService.findAll();
		request.setAttribute("companyList", companyList);
		request.setAttribute("catalogList", catalogList);
		request.getRequestDispatcher("/WEB-INF/pages/store/question/update.jsp").forward(request, response);
		//response.sendRedirect(request.getContextPath()+"/store/question?operation=list");
		
	}

	private void list(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//进入列表页，查询全部数据，存入session，调用显示
		QuestionService questionService = new QuestionServiceImp();
		int page =1;
		int size=5;
	   if((request.getParameterValues("page"))!=null){
		   page = Integer.parseInt(request.getParameter("page"));
	   }
	   if((request.getParameterValues("size"))!=null){
		   size = Integer.parseInt(request.getParameter("size"));
	   }
		
		PageInfo all = questionService.findAll(page, size);
		
		request.setAttribute("page", all);
		
		request.getRequestDispatcher("/WEB-INF/pages/store/question/list.jsp").forward(request, response);
		
	}

	private void toAdd(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		List<Company> companyList = companyService.findAll();
		List<Catalog> catalogList = catalogService.findAll();
		request.setAttribute("companyList", companyList);
		request.setAttribute("catalogList", catalogList);
	/*	List<Course> all =courseService.findAll();
		request.setAttribute("courseList", all);*/
		request.getRequestDispatcher("/WEB-INF/pages/store/question/add.jsp").forward(request, response);
		
	}
	
	/*private void save(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
		Question question = BeanUtil.fillBean(request, Question.class,"yyyy-MM-dd");
		QuestionService questionService = new QuestionServiceImp();
		questionService.save(question);
		list(request, response);
	}*/
	
	
     private void save(HttpServletRequest request, HttpServletResponse response) throws Exception {
		
    	 if(ServletFileUpload.isMultipartContent(request)){
 			//创建磁盘工厂
 			DiskFileItemFactory factory = new DiskFileItemFactory();
 			//通过servlet对象上传核心对象
 			ServletFileUpload fileUpload = new ServletFileUpload(factory);
 			//从reque 中获取对象
 			List<FileItem> fileItems = fileUpload.parseRequest(request);	
 			
 			Question question = BeanUtil.fillBean(fileItems, Question.class);
 			
 			boolean flag = false;
			for(FileItem item: fileItems){
				if(StringUtils.isNotBlank(item.getName())){
					flag = true;
					break;
				}
			}
 			String picture = questionService.save(question,flag);
 			QuestionService questionService = new QuestionServiceImp();
 	 		questionService.save(question,flag);
 			
 			for(FileItem item: fileItems){
 				System.out.println(item);
 				if(!item.isFormField()){
 					item.write(new File(this.getServletContext().getRealPath("upload"),picture));
 				}
 			}
 			
 		}
    	 	
 		list(request, response);
    	 
    	 
		/*Question question = BeanUtil.fillBean(request, Question.class,"yyyy-MM-dd");
		QuestionService questionService = new QuestionServiceImp();
		questionService.save(question);
		list(request, response);*/
		
	
	}
	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
